package com.websocket.sample.controller;

import com.websocket.sample.bean.Chat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * 3. 配置 controller
 */
@RestController
public class WebsocketController {
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 接受 /app/chat 的消息
     * @param chat
     */
    @MessageMapping("/chat")
    public void chat(Principal principal, Chat chat) {
        String from = principal.getName();
        chat.setFrom(from);
        simpMessagingTemplate.convertAndSendToUser(chat.getTo(), "/queue/chat", chat);

    }
}
